﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraCharts;
using DevExpress.Utils;
using TierService;
using OrderMgr.SysSetting;
using System.Data.SqlClient;
using TierApplication;


namespace OrderMgr.OrderInfo
{
    public partial class frmBuyInvoiceAppDetail : TierService.frmTemplate
    {
        #region "Member Variables"
        public string sFuncID;
        public TierService.Utility.OperateMode OpMode;
        public string sUserID;
        public string _OrderID = "";
        public Utility.OrderType _OrderType;
        public Utility.OrderStatus _AuditStatus;

        T_Order mOrder = new T_Order();
        SqlDataAdapter sdaOrderDetail = new SqlDataAdapter();
        DataSet dsOrderDetail = new DataSet();

        #endregion

        public frmBuyInvoiceAppDetail()
        {
            InitializeComponent();
        }

        private void frmBuyAuditDetail_Load(object sender, EventArgs e)
        {
            initForm();

            switch (OpMode)
            {
                case Utility.OperateMode.Query:

                    showInfo(_OrderID);
                    break;
                case Utility.OperateMode.Insert:
                    txtOrderDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                    txtOrderUserID.EditValue = TierService.Utility.gUserID;
                    txtOrderType.EditValue = ((int)_OrderType).ToString();
                    txtDepotID.EditValue = ((int)Utility.DepotType.Material).ToString();
                    txtRemark.Size = new Size(742, 83);
                    txtRemark.Location = new Point(82, 81);
                    BindOrderDetailLocal();
                    break;
                case Utility.OperateMode.Update:
                    showInfo(_OrderID);
                    break;
                case Utility.OperateMode.Delete:
                    break;
                default:
                    break;
            }

        }

        private void initForm()
        {
            Utility.DataToLookupComboxEx(txtOrderType, C_DMB.GetListByType(C_DMB.DType.OrderType.ToString()), "CodeID", "CodeName");
            Utility.DataToLookupComboxEx(txtDepotID, C_DMB.GetListByType(C_DMB.DType.DepotType.ToString()), "CodeID", "CodeName");
            Utility.DataToLookupComboxEx(txtOrderUserID, (new P_User()).GetList(""), "UserID", "UserName");
            Utility.DataToLookupComboxEx(txtAuditUserID, (new P_User()).GetList(""), "UserID", "UserName");
            //Utility.DataToLookupComboxEx(txtPayAuditUserID, (new P_User()).GetList(""), "UserID", "UserName");
            //Utility.DataToLookupComboxEx(txtPayUserID, (new P_User()).GetList(""), "UserID", "UserName");
            Utility.DataToLookupComboxEx(txtSupplierID, (new T_Supplier()).GetList(""), "SupplierID", "SupplierName");
            //Utility.DataToLookupComboxEx(txtPayType, C_DMB.GetListByType(C_DMB.DType.PayType.ToString()), "CodeID", "CodeName");
            //Utility.DataToLookupComboxEx(txtPayingUserID, (new P_User()).GetList(""), "UserID", "UserName");
            //Utility.DataToLookupComboxEx(txtInvoiceUserID, (new P_User()).GetList(""), "UserID", "UserName");

            txtOrderUserID.Enabled = false;
            txtOrderType.Enabled = false;

        }


        private void showInfo(string sID)
        {
            mOrder.GetModel(sID);
            this.txtOrderID.Text = mOrder.OrderID;
            if (mOrder.OrderDate != null)
                this.txtOrderDate.DateTime = mOrder.OrderDate.Value;
            this.txtOrderUserID.EditValue = mOrder.OrderUserID;
            this.txtOrderType.EditValue = mOrder.OrderType;
            this.txtDepotID.EditValue = mOrder.DepotID;
            this.txtAuditUserID.EditValue = mOrder.AuditUserID;
            if (mOrder.AuditDate != null)
                this.txtAuditDate.DateTime = mOrder.AuditDate.Value;
            this.txtRemark.Text = mOrder.Remark;
            this.txtSupplierID.EditValue = mOrder.SupplierID;

            //if (mOrder.InvoiceAuditRemark != "")
            //{
            //    txtDeAuditReson.Visible = true;
            //    txtDeAuditReson.Text = "审核退回原因：" + mOrder.InvoiceAuditRemark;
            //}

            //*****************Order Detail*****************//
            BindOrderDetail();
            BindOrderInvoiceInfo(_OrderID);
        }
        private void GetFormReturValue(string str)
        {
            string sID = str;
            if (sID != "")
            {
                showInfo(sID);
            }
        }


        private void btnClose_Click(object sender, EventArgs e)
        {
            //Close();
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }


        private void BindOrderDetailLocal()
        {
            DataTable dtOrderDetail = new TdsOrder.TOrderDetailDataTable();
            gcOrderDetail.DataSource = dtOrderDetail;
        }

        private void BindOrderDetail()
        {

            if (_OrderID == "") return;

            SqlConnection conn = new SqlConnection(DBUtility.DbHelperSQL.connectionString);

            SqlCommand cmd;
            SqlParameter pram;
            StringBuilder strSql = new StringBuilder();

            string sSql = "";
            sSql = "Select a.OrderDetailID,a.OrderID,a.ProductID,Floor(a.PlnQuantity) PlnQuantity,Floor(a.ShpQuantity) ShpQuantity,Floor(a.ActQuantity) ActQuantity,Floor(a.BckQuantity) BckQuantity,a.UnitPrice,(a.ActQuantity*a.UnitPrice) SumPrice, a.ProductNo,";
            sSql = sSql + " b.UnitName,b.SupplierName,b.Spec1,b.ProductName";
            sSql = sSql + " from T_OrderDetail a,S_Product b where a.ProductID=b.ProductID and a.OrderID='" + _OrderID + "'";
            cmd = new SqlCommand(sSql, conn);
            sdaOrderDetail.SelectCommand = cmd;

            strSql.Append("insert into T_OrderDetail(");
            strSql.Append("OrderDetailID,OrderID,ProductID,PlnQuantity,ShpQuantity,ActQuantity,BckQuantity,UnitPrice)");
            strSql.Append(" values (");
            strSql.Append("@OrderDetailID,@OrderID,@ProductID,@PlnQuantity,@ShpQuantity,@ActQuantity,@BckQuantity,@UnitPrice)");
            cmd = new SqlCommand(strSql.ToString(), conn);
            pram = new SqlParameter("@OrderID", SqlDbType.VarChar, 20);
            pram.Value = _OrderID;
            cmd.Parameters.Add(pram);
            cmd.Parameters.Add("@OrderDetailID", SqlDbType.VarChar, 10, "OrderDetailID");
            cmd.Parameters.Add("@ProductID", SqlDbType.VarChar, 10, "ProductID");
            cmd.Parameters.Add("@PlnQuantity", SqlDbType.Int, 4, "PlnQuantity");
            cmd.Parameters.Add("@ShpQuantity", SqlDbType.Int, 4, "ShpQuantity");
            cmd.Parameters.Add("@ActQuantity", SqlDbType.Int, 4, "ActQuantity");
            cmd.Parameters.Add("@BckQuantity", SqlDbType.Int, 4, "BckQuantity");
            cmd.Parameters.Add("@UnitPrice", SqlDbType.Decimal, 9, "UnitPrice");
            sdaOrderDetail.InsertCommand = cmd;

            strSql.Remove(0, strSql.Length);
            strSql.Append("update T_OrderDetail set ");
            //strSql.Append("ProductID=@ProductID,");
            strSql.Append("ProductID=@ProductID,");
            strSql.Append("PlnQuantity=@PlnQuantity,");
            strSql.Append("ShpQuantity=@ShpQuantity,");
            strSql.Append("ActQuantity=@ActQuantity,");
            strSql.Append("BckQuantity=@BckQuantity,");
            strSql.Append("UnitPrice=@UnitPrice");
            strSql.Append(" where OrderDetailID=@OrderDetailID ");
            cmd = new SqlCommand(strSql.ToString(), conn);
            cmd.Parameters.Add("@OrderDetailID", SqlDbType.VarChar, 10, "OrderDetailID");
            cmd.Parameters.Add("@ProductID", SqlDbType.VarChar, 10, "ProductID");
            cmd.Parameters.Add("@PlnQuantity", SqlDbType.Int, 4, "PlnQuantity");
            cmd.Parameters.Add("@ShpQuantity", SqlDbType.Int, 4, "ShpQuantity");
            cmd.Parameters.Add("@ActQuantity", SqlDbType.Int, 4, "ActQuantity");
            cmd.Parameters.Add("@BckQuantity", SqlDbType.Int, 4, "BckQuantity");
            cmd.Parameters.Add("@UnitPrice", SqlDbType.Decimal, 9, "UnitPrice");
            sdaOrderDetail.UpdateCommand = cmd;

            cmd = new SqlCommand("delete T_OrderDetail where OrderDetailID=@OrderDetailID", conn);
            cmd.Parameters.Add("@OrderDetailID", SqlDbType.VarChar, 10, "OrderDetailID");
            sdaOrderDetail.DeleteCommand = cmd;


            dsOrderDetail.Clear();

            sdaOrderDetail.Fill(dsOrderDetail);
            gcOrderDetail.DataSource = dsOrderDetail.Tables[0];
            //gvOrdersDetail.BestFitColumns();
        }


        private void BindOrderInvoiceInfo(string sOrderID)
        {
            T_OrderInvoice mOrderInvoice = new T_OrderInvoice();
            DataTable dtOrderInvoiceInfoDetail = mOrderInvoice.GetBuyInvoiceInfoByOrderID(sOrderID).Tables[0];
            gcBuyInvoice.DataSource = dtOrderInvoiceInfoDetail;
        }

        private void gvOrderDetail_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            DataRow dr = gvOrderDetail.GetDataRow(e.RowHandle);
            double UnitPrice, Quantity, Discount, SumPrice;

            try
            {
                UnitPrice = double.Parse(dr["UnitPrice"].ToString());
            }
            catch (Exception)
            {
                UnitPrice = 0;
            }

            try
            {
                Quantity = int.Parse(dr["ActQuantity"].ToString());
            }
            catch (Exception)
            {
                Quantity = 0;
            }

            SumPrice = UnitPrice * Quantity;
            //SumPrice = SumPrice - SumPrice * (100 - Discount) / 100;

            if (e.Column != clSumPrice)
            {
                dr["SumPrice"] = SumPrice.ToString("00000000000.00");
            }


            if (e.Column == clProductID)
            {
                string sProductID = dr["ProductID"].ToString();
                T_Product mProduct = new T_Product();
                mProduct.GetModel(sProductID);
                dr["ProductName"] = mProduct.ProductName;
                dr["PlnQuantity"] = 1;
                dr["ActQuantity"] = 1;
                dr["ShpQuantity"] = 1;
                dr["BckQuantity"] = 0;
                dr["SupplierName"] = mProduct.SupplierName;
                dr["UnitName"] = mProduct.UnitName;
                dr["UnitPrice"] = mProduct.UnitPrice;
                dr["SumPrice"] = mProduct.UnitPrice.ToString();
            }
        }

        private void btnAudit_Click(object sender, EventArgs e)
        {

            if (MessageBox.Show("是否要对此单据进行付款", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                return;
            string sOrderID = txtOrderID.Text;

            T_Order mOrder = new T_Order();
           // mOrder.Payment(sOrderID, Utility.gUserID);
            MessageBox.Show("付款成功");
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void btnDeAudit_Click(object sender, EventArgs e)
        {

            //if (MessageBox.Show("是否要退回此单据?", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            //    return;


            //string sOrderID = txtOrderID.Text;

            //T_Order mOrder = new T_Order();
            //mOrder.DeAuditPayApp(sOrderID, Utility.gUserID, txtPayReason.Text);
            //MessageBox.Show("审核退回成功");
            //DialogResult = System.Windows.Forms.DialogResult.OK;
        }



        private void btnAdd_Click(object sender, EventArgs e)
        {
            frmBuyInvoiceAppDetailInfo fDetail = new frmBuyInvoiceAppDetailInfo();
            fDetail.OpMode = TierService.Utility.OperateMode.Insert;
            fDetail._OrderID = txtOrderID.Text;
            fDetail._OrderStatus = Utility.OrderStatus.S0Input;
            fDetail._OrderType = Utility.OrderType.Buy;
            fDetail.ShowDialog();
            BindOrderInvoiceInfo(txtOrderID.Text);
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            if (gvBuyInvoice.RowCount < 1) return;
            DataRow dr = gvBuyInvoice.GetDataRow(gvBuyInvoice.FocusedRowHandle);
            string sID = dr["InvoiceID"].ToString();
            string sOrderStatus = dr["OrderStatus"].ToString();

            if (sOrderStatus == "1")
            {
                MessageBox.Show("此发票登记已提交审核，不能修改");
                return;
            }
            if (sOrderStatus == "2")
            {
                MessageBox.Show("此发票登记已审核，不能修改");
                return;
            }
            frmBuyInvoiceAppDetailInfo fDetail = new frmBuyInvoiceAppDetailInfo();
            fDetail.OpMode = Utility.OperateMode.Update;
            fDetail._InvoiceID = sID;
            fDetail.ShowDialog();

            BindOrderInvoiceInfo(txtOrderID.Text);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (gvBuyInvoice.RowCount < 1) return;
            DataRow dr = gvBuyInvoice.GetDataRow(gvBuyInvoice.FocusedRowHandle);
            string sID = dr["InvoiceID"].ToString();
            string sOrderStatus = dr["OrderStatus"].ToString();

            if (sOrderStatus == "1")
            {
                MessageBox.Show("此发票登记已提交审核，不能删除");
                return;
            }
            if (sOrderStatus == "2")
            {
                MessageBox.Show("此发票登记已审核，不能删除");
                return;
            }

            if (MessageBox.Show("是否要删除此订单记录，删除后将无法恢复!", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                return;


            T_OrderInvoice mOrder = new T_OrderInvoice();
            mOrder.Delete(sID);

            BindOrderInvoiceInfo(txtOrderID.Text);
        }

    }
}